package com.gitee.wsl.android.ext.store

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Environment
import android.os.FileObserver
import androidx.core.app.ActivityCompat
import com.gitee.wsl.android.ext.ApplicationInit.application
import com.gitee.wsl.jvm.ext.store.FileExt
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import java.io.*


fun FileExt.grantedStorage(): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        Environment.isExternalStorageManager()
    } else {
        ActivityCompat.checkSelfPermission(application, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
    }
}

fun FileExt.createFileObserver(file: File, events: Int, onEvent: (event: Int, path: String?) -> Unit): FileObserver {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        object : FileObserver(file, events) {
            override fun onEvent(event: Int, path: String?) {
                onEvent(event, path)
            }
        }
    } else {
        @Suppress("DEPRECATION")
        object : FileObserver(file.path, events) {
            override fun onEvent(event: Int, path: String?) {
                onEvent(event, path)
            }
        }
    }
}

fun File.subscribeFiles() = callbackFlow<List<File>> {
    fun sendFiles() {
        trySend(listFiles()?.toList() ?: emptyList())
    }
    sendFiles()
    val events = FileObserver.MOVED_TO or FileObserver.DELETE
    val observer = FileExt.createFileObserver(this@subscribeFiles, events) { _, _ ->
        sendFiles()
    }
    observer.startWatching()
    awaitClose { observer.stopWatching() }
}

